package com.stone.serverless.registry;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.system.SystemUtil;
import com.stone.serverless.registry.domain.ServiceInstance;
import com.stone.serverless.sdk.event.ComponentRunner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/28 9:19
 * @Version: 1.0.0
 */
public class NacosComponentRunner implements ComponentRunner {

    @Override
    public void run(Map<String, Object> environment, String commonScan) {

    }

    @Override
    public void componentUninstalled(ClassLoader classLoader) {
        DiscoveryService discoveryService = SpringUtil.getBean(DiscoveryService.class);
        String componentName = ReflectUtil.invoke(classLoader, "getComponentName");
        String version = ReflectUtil.invoke(classLoader, "getVersion");

        List<ServiceInstance> serviceInstances = discoveryService.selectInstances(componentName, true);

        if (CollUtil.isNotEmpty(serviceInstances)) {
            for (ServiceInstance serviceInstance : serviceInstances) {
                Map<String, String> metadata = serviceInstance.getMetadata();
                String o = metadata.get("service-version");
                if (CharSequenceUtil.isNotBlank(o) && o.equals(version)) {
                    String ip = serviceInstance.getIp();
                    int port = serviceInstance.getPort();
                    discoveryService.deregisterInstance(componentName, ip, port);
                }
            }
        }
    }

    @Override
    public void componentInstalled(ClassLoader classLoader) {
        String componentName = ReflectUtil.invoke(classLoader, "getComponentName");
        String version = ReflectUtil.invoke(classLoader, "getVersion");

        System.out.println(componentName + " " + version + " 依赖了注册中心 需要把他注册到注册中心去");
        String hostAddress = NetUtil.getLocalhost().getHostAddress();
        Map<String, String> metadata = new HashMap<>();
        metadata.put("service-version", version);
        metadata.put("os-name", SystemUtil.getOsInfo().getName());
        metadata.put("preserved.register.source", "SPRING");
        metadata.put("management.context-path", "/" + componentName + "/" + version);
        DiscoveryService discoveryService = SpringUtil.getBean(DiscoveryService.class);
        discoveryService.registerInstance(componentName, version, hostAddress, 8888, metadata);
    }

    @Override
    public void stop() {

    }
}
